<?php

namespace apiend\modules\work\models;

use Yii;
use yii\db\Exception;
use yii\helpers\Json;
use common\helpers\ArrayHelper;
use common\helpers\Url;
use common\helpers\DateHelper;
use common\models\survey\Survey;
use common\models\survey\SurveyAttach;
use common\models\survey\Substation;
use common\models\survey\DangerLevel;
use common\models\work\CompanyDepartment;
use common\logics\cascader\CategoryLogic;

/**
 * 预约基本信息模型
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class SurveyForm extends \common\base\FormModel {

    /**
     * @var string 数据原型模型
     */
    protected $modelClass = Survey::class;

    /**
     * @var integer 变电站ID
     */
    public $substation_id;

    /**
     * @var integer 检查项目ID
     */
    public $cid;

    /**
     * @var integer 隐患位置
     */
    public $position;

    /**
     * @var integer 隐患内容
     */
    public $content;

    /**
     * @var integer 隐患等级ID
     */
    public $danger_level_id;

    /**
     * @var integer 是否治理完成
     */
    public $solved;

    /**
     * @var integer 治理责任单位
     */
    public $department_id;

    /**
     * @var integer 负责人
     */
    public $director;

    /**
     * @var integer 治理前防范措施
     */
    public $pretreatment;

    /**
     * @var integer 治理措施
     */
    public $solution;

    /**
     * @var integer 计划治理时间
     */
    public $planTime;

    /**
     * @var integer 治理完成时间
     */
    public $completedTime;

    /**
     * @var array 治理完成时间
     */
    public $medias = [];

    /**
     * @var array 治理完成时间
     */
    public $attachs = [];

    /**
     * @var Substation 单位信息
     */
    private $_substation;

    /**
     * @return array validation rules
     */
    public function rules() {
        return [
            [['substation_id', 'danger_level_id', 'department_id', 'solved'], 'integer'],
            [['pretreatment', 'solution'], 'string'],
            [['planTime', 'completedTime'], 'date'],
            [['position', 'content'], 'string', 'max' => 255],
            [['director'], 'string', 'max' => 50],
            [['pretreatment', 'solution', 'position', 'content', 'director'], 'validateContent'],
            [['cid', 'medias', 'attachs'], 'safe'],
            [['substation_id'], 'validateSubStation'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => '排查表',
            'substation_id' => '变电站',
            'voltage_id' => '电压等级',
            'cid' => '检查项目/内容',
            'position' => '隐患位置',
            'content' => '隐患内容',
            'danger_level_id' => '隐患等级',
            'solved' => '是否治理完成',
            'department_id' => '治理责任单位',
            'director' => '治理负责人',
            'pretreatment' => '治理前防范措施',
            'solution' => '治理措施',
            'planTime' => '计划治理时间',
            'completedTime' => '治理完成时间',
            'status' => '状态',
        ];
    }

    /**
     * 微信小程序内容过滤
     * @param string $attribute `sign`
     */
    public function validateContent($attribute) {
        if ($this->hasErrors() || !$this->$attribute || !YII_ENV_PROD) {
            return;
        }
    }

    /**
     * @param string $attribute the attribute currently being validated
     */
    public function validateSubStation($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $model = Substation::findOne($this->$attribute);
        if (!$model) {
            return $this->addError($attribute, '变电站信息不存在或者已变更，请关闭重试');
        }
        $this->_substation = $model;
    }

    /**
     * @param Survey $model
     */
    public function setExtraAttributes($model) {
        if (!$model->isNewRecord) {
            $this->planTime = $model->plan_time ? date('Y-m-d', $model->plan_time) : '';
            $this->completedTime = $model->completed_at ? date('Y-m-d', $model->completed_at) : '';
            foreach ($model->attachs as $attach) {
                if ($attach->type) {
                    $this->attachs[] = $attach;
                } else {
                    $this->medias[] = $attach;
                }
            }
            $cids = [
                $model->c1,
                $model->c2,
                $model->c3,
                $model->category_id,
            ];
            $cid = 0;
            while (!$cid && count($cids) > 0) {
                $cid = array_pop($cids);
            }
            if ($cid) {
                $this->cid = $cid;
            }
        }
    }

    /**
     * 保存预约信息
     * @return Book
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('');
        }
        $user = $this->getUser();
        $model = $this->getModel();
        $uid = $model->user_id;
        if ($model->isNewRecord) {
            $uid = $user ? $user->id : 0;
            $model->user_id = $uid;
        }
        $substation = $this->_substation;

        $categoryIds = CategoryLogic::ancestors($this->cid, 'id');
        list($c1, $c2, $c3, $c4) = array_pad($categoryIds, 4, 0);

        $model->setAttributes([
            'substation_id' => $substation->id,
            'company_id' => $substation->company_id,
            'voltage_id' => $substation->voltage_id,
            'c1' => (int) $c1,
            'c2' => (int) $c2,
            'c3' => (int) $c3,
            'category_id' => (int) $c4,
            'position' => $this->position ?: '',
            'content' => $this->content ?: '',
            'danger_level_id' => (int) $this->danger_level_id,
            'solved' => (int) $this->solved,
            'department_id' => (int) $this->department_id,
            'director' => $this->director ?: '',
            'pretreatment' => $this->pretreatment ?: '',
            'solution' => $this->solution ?: '',
            'plan_time' => $this->planTime ? strtotime($this->planTime) : 0,
            'completed_at' => $this->completedTime ? strtotime($this->completedTime) : 0,
        ]);
        if ($this->solved) {
            $model->status = Survey::STATUS_SOLVED;
        } else {
            $model->status = Survey::STATUS_ACTIVE;
        }
        Yii::error($model->attributes);
        Yii::error($this->attributes);
        $medias = $this->medias;
        $attachs = $this->attachs;
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception($model->getErrorMsg());
            }
            $model->recordLog($user);
            $attachIds = [];
            foreach ($medias as $obj) {
                $path = ArrayHelper::getValue($obj, 'path');
                $attach = SurveyAttach::findOrNew([
                    'survey_id' => $model->id,
                    'path' => $path,
                ]);
                $attach->setAttributes([
                    'type' => 0,
                    'user_id' => $uid,
                    'size' => ArrayHelper::getValue($obj, 'size', 0),
                    'format' => ArrayHelper::getValue($obj, 'type', 'image') == 'image' ? 0 : 1,
                ]);
                if (!$attach->save()) {
                    throw new Exception($attach->getErrorMsg());
                }
                $attachIds[] = $attach->id;
            }
            foreach ($attachs as $obj) {
                $path = ArrayHelper::getValue($obj, 'path');
                $attach = SurveyAttach::findOrNew([
                    'survey_id' => $model->id,
                    'path' => $path,
                ]);
                $attach->setAttributes([
                    'type' => 1,
                    'user_id' => $uid,
                    'size' => ArrayHelper::getValue($obj, 'size', 0),
                    'format' => ArrayHelper::getValue($obj, 'type', 'image') == 'image' ? 0 : 1,
                ]);
                if (!$attach->save()) {
                    throw new Exception($attach->getErrorMsg());
                }
                $attachIds[] = $attach->id;
            }
            SurveyAttach::deleteAll([
                'and',
                ['survey_id' => $model->id],
                ['not in', 'id', $attachIds],
            ]);
            $transaction->commit();
        } catch (Exception $e) {
            // 记录回滚（事务回滚）
            $transaction->rollBack();
            return $this->dumpError($e->getMessage());
        }
        return $model;
    }

    /**
     * {@inheritdoc}
     */
    public function getUser() {
        $model = $this->getModel();
        if ($model->isNewRecord) {
            $adminer = Yii::$app->user->identity;
            return $adminer->appUser;
        }
        return $model->reporter;
    }

    /**
     * {@inheritdoc}
     */
    public function getSubstations() {
        $model = $this->getModel();
        if ($model->isNewRecord) {
            $adminer = Yii::$app->user->identity;
            $companyId = $adminer->companyIds;
        } else {
            $companyId = $model->company_id;
        }
        $query = Substation::findActive('t');
        $query->andWhere([
            't.company_id' => $companyId
        ]);
        $query->orderBy([
            't.listorder' => SORT_ASC,
            't.name' => SORT_ASC,
            't.status' => SORT_ASC,
        ]);
        $data = $query->all();
        $substations = [];
        foreach ($data as $item) {
            if (!isset($substations[$item->voltage_id])) {
                $substations[$item->voltage_id] = [
                    'id' => $item->voltage_id + 100000,
                    'name' => $item->voltage,
                    'children' => [],
                ];
            }
            $substations[$item->voltage_id]['children'][] = [
                'id' => $item->id,
                'name' => $item->name,
                'status' => $item->getMarkLabel('status'),
            ];
        }
        return array_values($substations);
    }

    /**
     * {@inheritdoc}
     */
    public function getCategorys() {
        return CategoryLogic::findDeeps(1)->all();
    }

    /**
     * {@inheritdoc}
     */
    public function getDangerLevels() {
        return DangerLevel::find()->active(DangerLevel::STATUS_ACTIVE)->all();
    }

    /**
     * {@inheritdoc}
     */
    public function getDepartments() {
        return CompanyDepartment::getOptionsList(true);
    }

    /**
     * {@inheritdoc}
     */
    public function getFormFields() {
        return $this->attributes;
    }

    /**
     * {@inheritdoc}
     */
    public function fields() {
        return [
            'options' => function() {
                return [
                    'substations' => $this->substations,
                    'categorys' => $this->categorys,
                    'dangerLevels' => $this->dangerLevels,
                    'departments' => $this->departments,
                ];
            },
            'form' => 'formFields',
        ];
    }

}
